package com.open.capacity.salary.service.impl;

import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.salary.dto.FormuleItemTypes;
import com.open.capacity.salary.util.MathCalculatorUtil;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.SysUserUtil;
import org.apache.commons.collections4.SetUtils;
import org.mvel2.MVEL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.salary.entity.GzItem;
import com.open.capacity.salary.dao.GzItemDao;
import com.open.capacity.salary.service.GzItemService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


@Service
public class GzItemServiceImpl implements GzItemService {

    @Autowired
    private GzItemDao gzItemDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int init(String companyId, String ztId) {
        gzItemDao.deleteByZtId(companyId, ztId);
        return gzItemDao.init(companyId, ztId);
    }

    /**
     * 添加
     *
     * @param gzItem
     */
    @Transactional(rollbackFor = Exception.class)
    public int save(GzItem gzItem) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        gzItem.setUpdateUserid(loginUser.getId());
        gzItem.setUpdateUsername(loginUser.getRealName());
        //gzItem.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        gzItem.setStatus(1);
        gzItem.setUpdateTime(new Date());
        gzItem.setIsMx(1);

        if (StringUtil.isNotEmpty(gzItem.getParentId())) {
            GzItem parent = gzItemDao.findById(gzItem.getParentId());
            if (parent != null) {
                parent.setIsMx(0);
                gzItemDao.update(parent);
            }
        }

        return gzItemDao.save(gzItem);
    }

    /**
     * 修改
     *
     * @param gzItem
     */
    @Transactional(rollbackFor = Exception.class)
    public int update(GzItem gzItem) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        gzItem.setUpdateUserid(loginUser.getId());
        gzItem.setUpdateUsername(loginUser.getRealName());

        GzItem old = gzItemDao.findById(gzItem.getId());
        gzItem.setUpdateTime(new Date());
        if (StringUtil.isNotEmpty(old.getParentId())) {
            GzItem parent = gzItemDao.findById(old.getParentId());
            List<GzItem> childrens = gzItemDao.findByParentId(old.getParentId());
            if (parent != null && childrens.size() == 1) {
                parent.setIsMx(1);
                gzItemDao.update(parent);
            }
        }
        if (StringUtil.isNotEmpty(gzItem.getParentId())) {
            GzItem parent = gzItemDao.findById(gzItem.getParentId());
            if (parent != null) {
                parent.setIsMx(0);
                gzItemDao.update(parent);
            }
        }

        return gzItemDao.update(gzItem);
    }

    @Override
    public int setFormula(String keyValue, String formula) {
        formula = formula.trim();
        GzItem item = gzItemDao.findById(keyValue);
        if (item != null) {
            verifyFormula(item.getCompanyId(), item.getZtId(), formula);
            item.setFormula(formula);
            gzItemDao.update(item);
            return 1;
        }
        return 0;
    }

    /**
     * 检查公式是否合法
     *
     * @param companyId
     * @param formulaStr
     */
    private void verifyFormula(String companyId, String ztId, String formulaStr) {
        List<GzItem> itemList = gzItemDao.findByZtId(companyId, ztId);
        List<String> itemNames = itemList.stream().map(t -> "$" + t.getName() + "").collect(Collectors.toList());

        Serializable serializable = MVEL.compileExpression(formulaStr);
        Assert.notNull(serializable, "表达式非法！");

        Set<String> specials = new HashSet<String>() {{
            add("$当月天数");
            add("$上月金额");
            add("$本月所得税");
            add("$上月所得税");
        }};
        Map<String, Object> params = new HashMap<>();
        String formulaStrNow = formulaStr;
        for (String item : specials) {
            params.put(item.replaceAll("（", "_1").replaceAll("）", "_2").replaceAll("、","_3").replaceAll("/","_4"), 1);
            formulaStrNow = StringUtil.replaceOnce(formulaStrNow, item, "1");
        }
        for (String item : itemNames) {
            params.put(item.replaceAll("（", "_1").replaceAll("）", "_2").replaceAll("、","_3").replaceAll("/","_4"), 1);
            formulaStrNow = StringUtil.replaceOnce(formulaStrNow, item, "1");
        }
        formulaStr = formulaStr.replaceAll("（", "_1").replaceAll("）", "_2").replaceAll("、","_3").replaceAll("/","_4");
        Object obj = MVEL.eval(formulaStr, params);


        //检查公式是否合法
        //MathCalculatorUtil.checkFormulaExpression(formulaStrNow);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public int delete(String id) {
        GzItem old = gzItemDao.findById(id);
        if (old != null) {
            GzItem parent = gzItemDao.findById(old.getParentId());
            List<GzItem> childrens = gzItemDao.findByParentId(old.getParentId());
            if (parent != null && childrens.size() == 1) {
                parent.setIsMx(1);
                gzItemDao.update(parent);
            }
        }
        return gzItemDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public GzItem findById(String id) {
        return gzItemDao.findById(id);
    }

    @Override
    public List<GzItem> findByZtId(String companyId, String ztId) {
        return gzItemDao.findByZtId(companyId, ztId);
    }

    @Override
    public List<String> findByZtIds(String companyId, String ztIds) {
        String[] ztArrs = ztIds.split(",");
        List<GzItem> list = gzItemDao.findByZtIds(companyId, ztArrs);
        return list.stream().map(GzItem::getName).distinct().collect(Collectors.toList());
    }

    @Override
    public List<GzItem> findByCompanyId(String companyId) {
        return gzItemDao.findByCompanyId(companyId);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<GzItem> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<GzItem> list = gzItemDao.findAll(params);
        PageInfo<GzItem> pageInfo = new PageInfo(list);

        return PageResult.<GzItem>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<GzItem> findAll(Map<String, Object> params) {
        return gzItemDao.findAll(params);
    }

}
